package org.tangdao.modules.file.web;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.tangdao.common.codec.EncodeUtils;
import org.tangdao.common.config.Global;
import org.tangdao.common.io.FileUtils;
import org.tangdao.common.lang.NumberUtils;
import org.tangdao.common.lang.StringUtils;
import org.tangdao.common.suports.BaseController;

@Controller	
public class UserfilesController extends BaseController {

	@RequestMapping(value={"/userfiles/**"})
    public String fileStreamDown(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return this.fileStreamDownImpl(request, response);
    }
	
	public String fileStreamDownImpl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String filePath = StringUtils.substringAfter(request.getRequestURI(), Global.USERFILES_BASE_URL);
		String preview = request.getParameter("preview");
		if (StringUtils.isNotBlank(preview)) {
			String fileUrl = request.getRequestURL().toString().replaceAll("(\\?|&)preview=([^&]*)(&|$)", "$1").replaceAll("[\\?|\\&]$", "");
			String requestUri = new StringBuilder("/file/").append(preview).append("/preview").toString();
			request.setAttribute("fileUrl", fileUrl);	
			request.setAttribute("fileUri", request.getRequestURI());	
			request.setAttribute("filePath", filePath);	
			request.setAttribute("javax.servlet.forward.request_uri", requestUri);	
			request.getRequestDispatcher(requestUri).forward(request, response);
			return null;
        }
		File temp;
		File ufur = new File(EncodeUtils.decodeUrl(filePath = Global.getUserfilesBaseDir(filePath)));
		if (!ufur.exists() && (temp = new File(EncodeUtils.decodeUrl(filePath,"GBK"))).exists()) {
			ufur = temp;
        }
		String fileName = request.getParameter("fileName");
		if(StringUtils.isEmpty(fileName)) {
			fileName = ufur.getName();
		}
		String fileNameNotExtension;
		if (NumberUtils.isCreatable(fileNameNotExtension = StringUtils.substringAfterLast(FileUtils.getFileNameWithoutExtension(fileName), "_$"))) {	
			fileName = StringUtils.replace(fileName, "_$" + fileNameNotExtension, "");	
        }	
		if (ufur.exists()) {
            FileUtils.downFile(ufur, request, response, fileName);
            return null;
        }
		return null;
	}
}
